package com.wgke.bluetooth.beans;

import com.google.gson.Gson;
import com.wgke.bluetooth.utils.FileUtil;

import java.util.List;

public class CommandGroup {
    public CommandBean header;
    public CommandBean crc;
    public List<CommandBean> body;
    public CommandBean footer;

    private static CommandGroup instance;

    public static CommandGroup getInstance(){
        if(instance==null){
            String json = FileUtil.loadJsFromAssets("caozuo.json");
            instance = new Gson().fromJson(json, CommandGroup.class);
        }
        return instance;
    }

    public List<CommandBean> getBody() {
        return body;
    }


    public String getCmd(CommandBean bean, int[] value) {
        byte[] buf = hexStringToByteArray(bean.cmd);//
        int length = buf.length + (value != null ? value.length : 0) + 2;
        byte[] byteArray = new byte[length];
        System.arraycopy(buf, 0, byteArray, 0, buf.length);
        for (int i = 0; i < (value != null ? value.length : 0); i++) {
            byteArray[buf.length + i] = (byte) value[i];
        }
        byteArray[byteArray.length - 2] = (byte) (byteArray.length + 4);//头部的所有长度都加上
        byteArray[byteArray.length - 1] = (byte) 0x00;

        return header.cmd + crc.getCrc(byteArray) + crc.bytesToHex(byteArray);
    }

    public static byte[] hexStringToByteArray(String hexString) {
        hexString = hexString.replaceAll("\\s", "").replace("0x", "");
        if (hexString.length() % 2 != 0) {
            hexString = "0" + hexString; // 补齐偶数长度
        }

        byte[] bytes = new byte[hexString.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            int index = i * 2;
            String hexPair = hexString.substring(index, index + 2);
            bytes[i] = (byte) Integer.parseInt(hexPair, 16);
        }
        return bytes;
    }
}
